package com.it.you.base.bingfa.jikeshijian;

import java.util.concurrent.atomic.AtomicLong;

public class SimulatedCAS {

    private volatile int count;

    // 实现count+=1 do {} while() 先执行一次do中的语句体，在判断while的条件，成立在执行do{}，反之程序往下执行
    public void addOne() {
        int newValue;
        do {
            newValue = count + 1; //①
        } while (count != cas(count, newValue)); //②
    }

    // 模拟实现CAS，仅用来帮助理解
    synchronized int cas(int expect, int newValue) {
        // 读目前count的值
        int curValue = count;
        // 比较目前count值是否==期望值
        if (curValue == expect) {
            // 如果是，则更新count的值
            count = newValue;
        }
        // 返回写入前的值
        return curValue;
    }

    public static void main(String[] args) {
        int count = 1;
        do {
            System.out.println("lalla");; //①
        } while (count == get(3)); //②

        AtomicLong atomicLong = new AtomicLong();
        long andIncrement = atomicLong.getAndIncrement();
        System.out.println(andIncrement);
        System.out.println(atomicLong);
    }

    public static int get(int a) {
        return a;
    }

}
